package cn.echo.ecc.service.impl;

import cn.echo.ecc.domain.CourseMarket;
import cn.echo.ecc.domain.CourseUserLearn;
import cn.echo.ecc.dto.PayExtParamDto;
import cn.echo.ecc.enums.GlobalExceptionCode;
import cn.echo.ecc.mapper.CourseUserLearnMapper;
import cn.echo.ecc.service.ICourseMarketService;
import cn.echo.ecc.service.ICourseUserLearnService;
import cn.echo.ecc.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hulan
 * @since 2022-09-30
 */
@Service
public class CourseUserLearnServiceImpl extends ServiceImpl<CourseUserLearnMapper, CourseUserLearn> implements ICourseUserLearnService {

    @Autowired
    private ICourseMarketService courseMarketService;

    @Override
    public CourseUserLearn getCourseUserLearnByCourseId(Long courseId,Long loginId) {
        Wrapper<CourseUserLearn> wrapper = new EntityWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("login_id",loginId);
        return selectOne(wrapper);
    }

    @Override
    public void saveCourseUserLearn(PayExtParamDto payExtParamDto) {
        String orderNo = payExtParamDto.getOrderNo();
        String courseIds = payExtParamDto.getCourseIds();
        Long userId = payExtParamDto.getUserId();
        // 1.参数校验
        AssertUtil.isNotEmpty(orderNo, GlobalExceptionCode.PARAM_IS_NOT_BULL);
        AssertUtil.isNotEmpty(courseIds, GlobalExceptionCode.PARAM_IS_NOT_BULL);
        AssertUtil.isNotNull(userId,GlobalExceptionCode.PARAM_IS_NOT_BULL);
        // 2.转换courseIds格式
        String[] split = courseIds.split(",");
        List<Long> courseIdsList = Arrays.stream(split).map(id -> Long.valueOf(id)).collect(Collectors.toList());
        // 3.查询用户和课程的关系表和课程销售表，封装为map集合
        Map<Long, CourseUserLearn> courseUserLearnMap = selectByUserId(userId).stream().collect(Collectors.toMap(CourseUserLearn::getCourseId, courseUserLearn -> courseUserLearn));
        Map<Long, CourseMarket> courseMarketMap = courseMarketService.selectBatchIds(courseIdsList).stream().collect(Collectors.toMap(CourseMarket::getId, courseMarket -> courseMarket));
        // 4.根据courseId保存用户和课程的关系表
        for (Long courseId : courseIdsList) {
            CourseUserLearn courseUserLearn = courseUserLearnMap.get(courseId);
            Date now = new Date();
            Integer validDays = courseMarketMap.get(courseId).getValidDays();
            // 4.1.用户没有购买过该课程
            if (courseUserLearn == null) {
                courseUserLearn = new CourseUserLearn();
                courseUserLearn.setCourseId(courseId);
                courseUserLearn.setCourseOrderNo(orderNo);
                courseUserLearn.setCreateTime(now);
                courseUserLearn.setLoginId(userId);
                courseUserLearn.setState(CourseUserLearn.PURCHASED_STATE);
                courseUserLearn.setStartTime(now);
                courseUserLearn.setEndTime(DateUtils.addDays(now,validDays));
                insert(courseUserLearn);
            } else {
                // 4.2.购买过
                if (courseUserLearn.getState() == CourseUserLearn.EXPIRED_STATE) {
                    // 4.2.1已过期
                    courseUserLearn.setStartTime(now);
                    courseUserLearn.setEndTime(DateUtils.addDays(now,validDays));
                    courseUserLearn.setState(CourseUserLearn.PURCHASED_STATE);
                    courseUserLearn.setCourseOrderNo(orderNo);
                } else {
                    // 4.2.2未过期
                    courseUserLearn.setEndTime(DateUtils.addDays(now,validDays));
                    courseUserLearn.setCourseOrderNo(orderNo);
                }
                updateById(courseUserLearn);
            }
        }
    }

    private List<CourseUserLearn> selectByUserId(Long userId) {
        Wrapper<CourseUserLearn> wrapper = new EntityWrapper<>();
        wrapper.eq("login_id",userId);
        return selectList(wrapper);
    }
}
